﻿module Sustainalytics.ProductInvolvement {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    // Assessments List controller
    export class CompanyAssessmentListController {

        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of assessments
        public assessmentsList: PIAssessmentListDto[];

        // total number of assessments
        public assessmentCount: number;

        private scopeDestroyed: boolean;

        // permissions
        //public piPermissions: ProductInvolvement.Security.PIPermissions;

        public hasMultiCompanyPI: boolean;

        public notIncludedInUserUniverses: boolean;
        public noEvidenceFoundInIndicatorsOfInterest: boolean;
        public noClaims: boolean;

        private accountId: string;
        private userId: string;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private CompanyAssessmentService: ICompanyAssessmentService,
            private PIPermissionsService: ProductInvolvement.Security.IPIPermissionsService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects) {

            var ctx = this;

            $scope['assessmentsList'] = ctx;

            ctx.scopeDestroyed = false;


            // get permissions
            ctx.hasMultiCompanyPI = ctx.PIPermissionsService.hasMultiCompanyPI();

            if (!ctx.hasMultiCompanyPI) {
                // redirect to Overview tab
                //this.$location.path('/research/' + ctx.companyNameQueryString);
            }

            ctx.orderByCol = "CompanyNameLowerCase";
            ctx.orderByAsc = true;

            //get accountId and userId to invalidate cache
            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            ctx.handlePagerChanged();
            ctx.handleScopeDestroyed();
        }
            
        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function () {
                ctx.scopeDestroyed = true;
            });            
        }

        // search for company assessments when pager changes
        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                ctx.getAssessments();
            });
        }


        // order list of portfolios
        public setOrderByCol(col: string) {
            var ctx = this;

            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            }
            else {
                ctx.orderByCol = col;
                ctx.orderByAsc = true;
            }
            ctx.getAssessments();
        }

        // search list of assessments
        public getAssessments(): ng.IPromise<Common.PagedList<PIAssessmentListDto>> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;
            
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
            {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();

            //get assessments count
            var pagedListPromise: ng.IPromise<Common.PagedList<PIAssessmentListDto>> =
                ctx.CompanyAssessmentService.getCompanyAssessmentsPagedList(skip, take, [ctx.orderByCol], ctx.orderByAsc, ctx.accountId, ctx.userId);

            pagedListPromise
                .then(function (pagedList: Common.PagedList<PIAssessmentListDto>)
                {
                    ctx.assessmentsList = pagedList.items;
                    ctx.assessmentCount = pagedList.totalItemsCount;
                    pager.setTotalItemsCount(pagedList.totalItemsCount);
                },
                (reason) =>
                {
                    if (reason.status == 404) {
                        if (reason.data.errCode == "PICompanyAssessmentShortReportEmptyNoUniversesException") {
                            ctx.notIncludedInUserUniverses = true;
                        }
                        if (reason.data.errCode == "PICompanyAssessmentShortReportEmptyNoClaimsException") {
                            ctx.noEvidenceFoundInIndicatorsOfInterest = true;
                        }
                    }
                    if (reason.status == 401) {
                        ctx.noClaims = true;
                    }
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return pagedListPromise;
        }   
    }

    // register controller with ProductInvolvement module
    angular.module('Sustainalytics.ProductInvolvement').controller('CompanyAssessmentListController', function (
        $rootScope: ng.IScope,
        $scope: ng.IScope,
        $q: ng.IQService,
        $location: ng.ILocationService,
        CompanyAssessmentService : ICompanyAssessmentService,
        PIPermissionsService: ProductInvolvement.Security.IPIPermissionsService,
        notificationFactory: Common.INotificationFactory,
        staticObjects: Common.IStaticObjects) {
        var ctrl = new Sustainalytics.ProductInvolvement.CompanyAssessmentListController($rootScope, $scope, $q, $location, CompanyAssessmentService, PIPermissionsService, notificationFactory, staticObjects);
        return ctrl;
    });
} 